const http = require('http')
const path = require('path')
const fs = require('fs')
const pug = require('pug')
const mime = require('mime/lite');
const promisify = require('util').promisify

const stat = promisify(fs.stat)
const readdir = promisify(fs.readdir)

const CONFIG = require('./config/defaultConfig.js')

const server = http.createServer((req, res) => {
  const filePath = path.join(CONFIG.root, req.url)

  fnRoute(req, res, filePath)
  
}).listen(CONFIG.port)

// console.log(mime.getType('json'))

let fnRoute = async (req, res, filePath) => {
  const stats = await stat(filePath)
  const extname = (path.extname(req.url))
  const mimeType = mime.getType(extname)
  try {
    if(stats.isFile()) {
      res.writeHeader(200, {
        'content-type': `${mimeType};charset=utf-8`
      })
      
      fs.createReadStream(filePath).pipe(res)
    } else if(stats.isDirectory()){
      fnReadDir(req, res, filePath)
      
    }
  } catch (error) {
    res.writeHeader(404, {
      'content-type': 'text/html'
    })
    res.write('<h2>抱歉，您请求的地址不存在!!!</h2>')
  }
}

let fnReadDir = async (req, res, filePath) => {
  const files = await readdir(filePath)
  const templPath = path.join(__dirname, './views/dir_links.pug')
  try {
    res.writeHeader(200, {
      'content-type': 'text/html;charset=utf-8'
    })

    const dir = path.relative(CONFIG.root, filePath)
    dataTempl = {
      files,
      dir: dir ? `/${dir}/`: ''
    }
   
    pug.renderFile(templPath, dataTempl, (err, data) => {
      if(err) console.log('render fail!!!', err)
      else{
        res.end(data)
      }
    })
  } catch (error) {
    // console.log(error)
  }
}